<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Services\ASRService;
use App\Services\TTSService;
use App\Services\OpenAIService;
use App\Services\XFYUNService;

class ChatController extends Controller
{
    public function index(): \Illuminate\Http\JsonResponse
    {
        return response()->json([
            "code" => 0
        ]);
    }

    public function postFile(Request $request): \Illuminate\Http\JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|mimes:mp3,wav,m4a',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'code' => 100,
                'message' => "文件格式不合法"
            ]);
        }

        $mp3File = $request->file('file');
        $model = $request->input("model");
        $sessionId = $request->input("sessionId ");
        $cacheKey = "ChatMsg_".$sessionId;
        $messages = Cache::get($cacheKey, function () {
            return [];
        });
        try {
            $mp3FilePath = $this->saveFileLocal($mp3File);
            $inText = ASRService::audioToText($mp3FilePath);
            $messages[] = [
                'role' => 'user',
                'content' => $inText
            ];
            $returnText = "";
            switch ($model) {
                case "OpenAI-chatGPT-3.5":
                    $returnText = OpenAIService::chat($messages, "gpt-3.5-turbo");
                    break;
                case "OpenAI-chatGPT-4":
                    $returnText = OpenAIService::chat($messages, "gpt-4");
                    break;
                case "XFYun-spark-2":
                    $returnText = XFYUNService::chat($messages);
                    break;
            }
            if (!$returnText) {
                throw new Exception('returnText为空，任务失败');
            }
            Log::info("assistantContent:" . $returnText);
            $messages[] = [
                'role' => 'assistant',
                'content' => $returnText
            ];
            Cache::put($cacheKey, $messages, $seconds = 3600);
            // 如果文字过长，则不转语音
            if (mb_strlen($returnText) > 300) {
                $returnMp3File = "";
            } else {
                $returnMp3File = TTSService::textToAudio($returnText);
            }
            return response()->json([
                'code' => 0,
                'data' => [
                    'message' => $returnText,
                    'file' => $returnMp3File
                ]
            ]);
        } catch (Exception $e) {
            return response()->json([
                'code' => 100,
                'message' => $e->getMessage()
            ]);
        }
    }

    protected function saveFileLocal(UploadedFile $file): bool|string
    {
        $requestId = Str::random(30);
        $fileName = $requestId . "." . $file->extension();
        return $file->storeAs('images', $fileName);
    }
}
